package generator;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

import utilities.WeightedRandom;

import Player.Enemy;

import command.Attack;

import concept.Attributes;



public class EnemyGenerator {

	public static Enemy next(int nearbyLevel){
		int level = nearbyLevel + w.next() - 2; // + o - 2 livelli
		if(level<=0)
			level = 1;
		Enemy e = new Enemy(new StringGenerator().next(), level, randomAttacks(level), randomAttributes(level));
		return e;
	}
	
	@SuppressWarnings("resource")
	public static ArrayList<Attack> randomAttacks(int level){
		ArrayList<Attack> possibleAttack = new ArrayList<Attack>();
		Scanner sc = null;
		try {
			sc = new Scanner(allAttack);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		while(sc.hasNextLine()){
			String name = sc.next();
			int attLevel = sc.nextInt();
			int damage = sc.nextInt();
			int perc = sc.nextInt();
			String type = sc.next();
			if(attLevel<=level)
				possibleAttack.add(new Attack(name, Attack.Type.valueOf(type.toUpperCase()), attLevel, damage, perc, true));
		}
		ArrayList<Attack> attack = new ArrayList<Attack>();
		for(int i = 0; i<Math.sqrt((double)level); i++)
			attack.add(possibleAttack.get(r.nextInt(possibleAttack.size())));
		return attack;
	}
	
	public static Attributes randomAttributes(int level){
		int i=0,s=1,a=0,d=0;
		for(int j = 0; j<2+3*(level-1); j++){
			boolean trovato = false;
			while(!trovato){
				switch (r.nextInt(4)){
				case 0: i++; break;
				case 1: s++; break;
				case 2: a++; break;
				case 3: d++; break;
				}
				trovato = true;
				if(s>level){
					s--;
					trovato = false;
				}
			}
		}
		return new Attributes(i, s, a, d);
	}
	
	private static Random r = new Random();
	private static WeightedRandom w = new WeightedRandom(new double[]{5, 30, 45, 15, 5});
	private static File allAttack = new File("attacks.dat");
}
